import { DataSource, DataSourceOptions } from 'typeorm';
import { ConfigService } from '../config/config.service';
import { Message } from '../../domain/entities/message.entity';
import { Session } from '../../domain/entities/session.entity';
import { User } from '../../domain/entities/user.entity';
import { Token } from '../../domain/entities/token.entity';

export function createDataSource(configService: ConfigService): DataSource {
  const dbType = configService.getDatabaseType();
  const dbUrl = configService.getDatabaseUrl();
  
  const commonOptions = {
    entities: [Message, Session, User, Token],
    synchronize: true, // 开发环境使用，生产环境应该关闭
    logging: configService.getLogLevel() === 'debug',
  };

  let options: DataSourceOptions;

  switch (dbType) {
    case 'mysql':
      options = {
        ...commonOptions,
        type: 'mysql' as const,
        url: dbUrl,
      };
      break;
    case 'mongodb':
      options = {
        ...commonOptions,
        type: 'mongodb' as const,
        url: dbUrl,
      };
      break;
    case 'sqlite':
    default:
      options = {
        ...commonOptions,
        type: 'sqlite' as const,
        database: dbUrl,
      };
      break;
  }

  return new DataSource(options);
}